package com.develop.data.loan.converter;

import com.develop.data.loan.option.constraint.CodedOption;
import com.develop.exception.BusinessException;
import com.develop.exception.BusinessExceptionInfo;
import org.springframework.core.convert.converter.Converter;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


//
public class CodedEnumConverter<Enumerable extends Enum<?> & CodedOption> implements Converter<String, Enumerable> {

    private Map<String, Enumerable> code2constant = new HashMap<String, Enumerable>();

    public CodedEnumConverter(Class<Enumerable> enumerable) {
        Arrays.stream(enumerable.getEnumConstants()).forEach(
                enumConstant -> {
                    try {
                        Method methodGetCode = enumerable.getDeclaredMethod("getCode");
                        this.code2constant.put(methodGetCode.invoke(enumConstant).toString(), enumConstant);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
    }

    @Override
    public Enumerable convert(String code) {
        return Optional.of(code)
                .map(code2constant::get)
                .orElseThrow(() -> new BusinessException(BusinessExceptionInfo.CONVERSION));
    }
}
